package com.example.jasonsun.sharelib;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.example.jasonsun.sharelib.activity.ShareActivity;
import com.example.jasonsun.sharelib.config.Cache;
import com.example.jasonsun.sharelib.platform.QQPlatform;
import com.example.jasonsun.sharelib.platform.SharePlatform;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.net.RequestListener;
import com.sina.weibo.sdk.utils.LogUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    /**
     * SSO 授权认证实例
     */
    private SsoHandler mSsoHandler;
    /**
     * 授权认证所需要的信息
     */
    private AuthInfo mAuthInfo;
    /**
     * 登陆认证对应的listener
     */
    private AuthListener mLoginListener = new AuthListener();
    /**
     * 登出操作对应的listener
     */
    private LogOutRequestListener mLogoutListener = new LogOutRequestListener();
    private TextView mTokenTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.inflateMenu(R.menu.my);
        ((TextView) toolbar.findViewById(R.id.title)).setText("hello world");
        mTokenTextView = (TextView) findViewById(R.id.token);
        findViewById(R.id.login_xlweibo).setOnClickListener(this);
        findViewById(R.id.logout).setOnClickListener(this);
        findViewById(R.id.login_qq).setOnClickListener(this);
        findViewById(R.id.logout_qq).setOnClickListener(this);
        findViewById(R.id.test).setOnClickListener(this);

        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                if (item.getItemId() == R.id.share) {
                    startActivity(new Intent(getBaseContext(), ShareActivity.class));
                    return true;
                } else {
                    return false;
                }
            }
        });
    }

    @Override
    public void onClick(View view) {
    }

    private void test() {
    }

    private SharePlatform platform;

    private void logoutQQ() {
        platform.logout();
    }

    private void loginWithQQ() {
        if (platform == null) {
            platform = new QQPlatform(this);
        }
        platform.login();
    }

    private void logout() {
        new LogoutAPI(this, Cache.sina_app_key, AccessTokenKeeper.readAccessToken(this)).logout(mLogoutListener);
    }

    private void loginWithXlWeibo() {
        // 创建授权认证信息
        mAuthInfo = new AuthInfo(this, Cache.sina_app_key, Cache.sina_redirect_url, Cache.sina_scope);
        if (null == mSsoHandler && mAuthInfo != null) {
            mSsoHandler = new SsoHandler(this, mAuthInfo);
        }

        if (mSsoHandler != null) {
            mSsoHandler.authorize(mLoginListener);
        } else {
            LogUtil.e("hello", "Please setWeiboAuthInfo(...) for first");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d("hello", "-->onActivityResult " + requestCode + " resultCode=" + resultCode);
        if (requestCode == com.tencent.connect.common.Constants.REQUEST_LOGIN ||
                requestCode == com.tencent.connect.common.Constants.REQUEST_APPBAR) {
            ((QQPlatform) platform).onActivityResultData(requestCode, resultCode, data, null);
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 登入按钮的监听器，接收授权结果。
     */
    private class AuthListener implements WeiboAuthListener {
        @Override
        public void onComplete(Bundle values) {
            Oauth2AccessToken accessToken = Oauth2AccessToken.parseAccessToken(values);
            if (accessToken != null && accessToken.isSessionValid()) {
                String date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(
                        new java.util.Date(accessToken.getExpiresTime()));
                String format = getString(R.string.weibosdk_demo_token_to_string_format_1);
                mTokenTextView.setText(String.format(format, accessToken.getToken(), date));

                AccessTokenKeeper.writeAccessToken(getApplicationContext(), accessToken);
            }

            getUsername();
        }

        @Override
        public void onWeiboException(WeiboException e) {
            Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel() {
            Toast.makeText(MainActivity.this,
                    R.string.weibosdk_demo_toast_auth_canceled, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 微博 OpenAPI 回调接口。
     */
    private RequestListener mListener = new RequestListener() {
        @Override
        public void onComplete(String response) {
            if (!TextUtils.isEmpty(response)) {
                LogUtil.i("hello", response);
                // 调用 User#parse 将JSON串解析成User对象
                User user = User.parse(response);
                if (user != null) {
                    Toast.makeText(getBaseContext(), "获取User信息成功，用户昵称：" + user.screen_name, Toast.LENGTH_LONG).show();
                    Log.d("hello", "name: " + user.id);
                } else {
                    Toast.makeText(getBaseContext(), response, Toast.LENGTH_LONG).show();
                }
            }
        }

        @Override
        public void onWeiboException(WeiboException e) {
            LogUtil.e("hello", e.getMessage());
            ErrorInfo info = ErrorInfo.parse(e.getMessage());
            Toast.makeText(getBaseContext(), info.toString(), Toast.LENGTH_LONG).show();
        }
    };

    private void getUsername() {
        // 获取当前已保存过的 Token
        Oauth2AccessToken mAccessToken = AccessTokenKeeper.readAccessToken(this);
        // 获取用户信息接口
        UsersAPI mUsersAPI = new UsersAPI(this, Cache.sina_app_key, mAccessToken);

        if (mAccessToken != null && mAccessToken.isSessionValid()) {
            long uid = Long.parseLong(mAccessToken.getUid());
            mUsersAPI.show(uid, mListener);
        }
    }


    /**
     * 登出按钮的监听器，接收登出处理结果。（API 请求结果的监听器）
     */
    private class LogOutRequestListener implements RequestListener {
        @Override
        public void onComplete(String response) {
            if (!TextUtils.isEmpty(response)) {
                try {
                    JSONObject obj = new JSONObject(response);
                    String value = obj.getString("result");

                    if ("true".equalsIgnoreCase(value)) {
                        AccessTokenKeeper.clear(MainActivity.this);
                        mTokenTextView.setText(R.string.weibosdk_demo_logout_success);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onWeiboException(WeiboException e) {
            mTokenTextView.setText(R.string.weibosdk_demo_logout_failed);
        }
    }

//    /**
//     * 当 SSO 授权 Activity 退出时，该函数被调用。
//     */
//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
//    }
}
